package com.bupt.ilink.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bupt.ilink.entity.*;
import com.bupt.ilink.mapper.DatasetMetadataMapper;
import com.bupt.ilink.service.*;
import com.bupt.ilink.utils.R;
import com.bupt.ilink.utils.SnowflakeIdGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("/dataset")
@RestController
public class DatasetController {
    @Autowired
    private DatasetMetadataService datasetMetadataService;

    @Autowired
    private DatasetMetadataMapper datasetMetadataMapper;

    @Autowired
    private DatasetTagsService datasetTagsService;

    @Autowired
    private DatasetFavoriteService datasetFavoriteService;

    @Autowired
    private OssService ossService;


    //  收藏和用户相关联
    @PostMapping("/favoriteAllDataset")
    public R favoriteAllDataset(@RequestBody String jsonString,
                                @AuthenticationPrincipal UserDetails userDetails) {

        JSONObject jsonObject = new JSONObject(jsonString);
        String targetId = jsonObject.getString("targetId");

        User user = (User) userDetails;
        //  收藏和用户id绑定
        String userId = user.getUserId();

        // 获取数据集元数据
        DatasetMetadata metadata = datasetMetadataMapper.selectById(targetId);
        System.out.println("分享量");
        System.out.println(targetId);
        System.out.println(metadata);
        DatasetFavorite favorite = new DatasetFavorite();

        if (metadata != null) {
            // 增加收藏次数
            datasetMetadataService.incrementFavoriteNum(Long.valueOf(targetId));

            //  在DatasetFavorite中建立关联
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
            Long favoriteId = idGenerator.nextId();

            favorite.setFavoriteId(favoriteId);
            favorite.setUserId(userId);
            favorite.setDatasetId(Long.valueOf(targetId));
            favorite.setAddedAt(new Date());
            return R.ok("收藏量+1并且同步用户"+user.getUsername());
        } else {
            return R.failure("数据集不存在");
        }
    }

    /*
    编写人：张博
    用途：只查找公开数据集
     */
    @GetMapping("/get_public_dataset_metadata")
    public IPage<DatasetResponse> getPublicDatasetMetadata(
            @AuthenticationPrincipal UserDetails userDetails,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String keywords,
            @RequestParam(required = false) String tag,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size) {

        User user = (User) userDetails;
        String userId = user.getUserId();

        // 使用 LambdaQueryWrapper 替代 QueryWrapper
        LambdaQueryWrapper<DatasetMetadata> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 添加 access_level 是 public 的条件
        lambdaQueryWrapper.eq(DatasetMetadata::getAccessLevel, "public");

        // 处理 keyword 和 tag 的条件
        if (keywords != null && !keywords.isEmpty()) {
            lambdaQueryWrapper.like(DatasetMetadata::getName, keywords);
        }

        if (tag != null && !tag.isEmpty()) {
            List<Long> datasetIdsWithTag = datasetTagsService.list(
                    new LambdaQueryWrapper<DatasetTags>().eq(DatasetTags::getTag, tag)
            ).stream().map(DatasetTags::getDatasetId).collect(Collectors.toList());

            if (!datasetIdsWithTag.isEmpty()) {
                lambdaQueryWrapper.in(DatasetMetadata::getDatasetId, datasetIdsWithTag);
            } else {
                // 如果没有符合条件的标签，返回空结果
                return new Page<>(page, size);
            }
        }

        // 处理排序条件
        if ("最热".equals(sortBy)) {
            lambdaQueryWrapper.orderByDesc(DatasetMetadata::getDownloadNum);
        } else if ("最新".equals(sortBy)) {
            lambdaQueryWrapper.orderByDesc(DatasetMetadata::getCreatedTime);
        }

        // 执行分页查询
        IPage<DatasetMetadata> datasetPage =
                datasetMetadataService.page(new Page<>(page, size), lambdaQueryWrapper);

        // 将查询结果转换为 DatasetResponse 对象
        List<DatasetResponse> datasetResponses = datasetPage.getRecords().stream()
                .map(dataset -> {
                    DatasetResponse response = new DatasetResponse();
                    response.setDatasetId(dataset.getDatasetId());
                    response.setName(dataset.getName());
                    response.setDescription(dataset.getDescription());
                    response.setCreatorName(dataset.getCreatorName());
                    response.setCreatedTime(dataset.getCreatedTime());
                    response.setAccessLevel(dataset.getAccessLevel());

                    String imageUrl = ossService.getImageUrl
                            ("dataset-square","image/" + dataset.getDatasetId());
                    response.setImagePath(imageUrl);
                    response.setUrl(dataset.getUrl());
                    response.setClickNum(dataset.getClickNum());
                    response.setDownloadNum(dataset.getDownloadNum());
                    response.setShareNum(dataset.getShareNum());
                    response.setFavoriteNum(dataset.getFavoriteNum());

                    // 设置标签信息
                    List<String> tags = datasetTagsService.list(
                            new LambdaQueryWrapper<DatasetTags>()
                                    .eq(DatasetTags::getDatasetId, dataset.getDatasetId())
                    ).stream().map(DatasetTags::getTag).collect(Collectors.toList());
                    response.setTags(tags);

                    return response;
                }).collect(Collectors.toList());

        // 返回分页结果
        Page<DatasetResponse> datasetResponsePage = new Page<>(page, size);
        datasetResponsePage.setRecords(datasetResponses);
        datasetResponsePage.setTotal(datasetPage.getTotal());
        datasetResponsePage.setCurrent(datasetPage.getCurrent());
        datasetResponsePage.setSize(datasetPage.getSize());

        return datasetResponsePage;
    }


    //  杂糅查找，和用户关联
    @GetMapping("/get_dataset_metadata")
    public IPage<DatasetResponse> getDatasetMetadata(
            @AuthenticationPrincipal UserDetails userDetails,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String collection,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String tag,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "12") int size) {

        User user = (User) userDetails;
        String userId = user.getUserId();

        QueryWrapper<DatasetMetadata> queryWrapper = new QueryWrapper<>();

        // 处理“我收藏的”条件
        if ("我收藏的".equals(collection)) {
            List<Long> favoriteDatasetIds = datasetFavoriteService.list(
                    new QueryWrapper<DatasetFavorite>().eq("user_id", userId)
            ).stream().map(DatasetFavorite::getDatasetId).collect(Collectors.toList());

            if (!favoriteDatasetIds.isEmpty()) {
                queryWrapper.in("dataset_id", favoriteDatasetIds);
            } else {
                // 如果用户没有收藏任何课程，返回空结果
                return new Page<>(page, size);
            }
        }else{
            //这里添加所有DatasetMetadata的access_level是public的
            queryWrapper.eq("access_level", "public");
        }

        // 处理 keyword 和 tag 的条件
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like("dataset_name", keyword);
        }

        //  这里需要修改，是DatasetTags类中的tag匹配
        if (tag != null && !tag.isEmpty()) {
            List<Long> datasetIdsWithTag = datasetTagsService.list(
                    new QueryWrapper<DatasetTags>().eq("tag", tag)
            ).stream().map(DatasetTags::getDatasetId).collect(Collectors.toList());

            if (!datasetIdsWithTag.isEmpty()) {
                queryWrapper.in("dataset_id", datasetIdsWithTag);
            } else {
                // 如果没有符合条件的标签，返回空结果
                return new Page<>(page, size);
            }
        }

        // 处理排序条件
        if ("最热".equals(sortBy)) {
            queryWrapper.orderByDesc("download_num");
        } else if ("最新".equals(sortBy)) {
            queryWrapper.orderByDesc("created_time");
        }

        // 执行分页查询
        IPage<DatasetMetadata> datasetPage =
                datasetMetadataService.page(new Page<>(page, size), queryWrapper);

        // 将查询结果转换为 CourseResponse 对象
        List<DatasetResponse> datasetResponses = datasetPage.getRecords().stream()
                .map(dataset -> {
                    DatasetResponse response = new DatasetResponse();
                    response.setDatasetId(dataset.getDatasetId());
                    response.setName(dataset.getName());
                    response.setDescription(dataset.getDescription());
                    response.setCreatorName(dataset.getCreatorName());
                    response.setCreatedTime(dataset.getCreatedTime());
                    response.setAccessLevel(dataset.getAccessLevel());

                    String imageUrl = ossService.getImageUrl
                            ("dataset-square","image/" + dataset.getDatasetId());
                    response.setImagePath(imageUrl);
                    response.setUrl(dataset.getUrl());
                    response.setClickNum(dataset.getClickNum());
                    response.setDownloadNum(dataset.getDownloadNum());
                    response.setShareNum(dataset.getShareNum());
                    response.setFavoriteNum(dataset.getFavoriteNum());

//                    if(course.getCourseImage() != null)
//                    {
//                        response.setCourseImage(ossService.getFileUrl(course.getCourseImage()));
//                    }else{
//                        response.setCourseImage(null);
//                    }
//                    System.out.println("课程封面"+response.getCourseImage());

                    // 设置标签信息，需要修改此处
                    List<String> tags = datasetTagsService.list(
                            new QueryWrapper<DatasetTags>()
                                    .eq("dataset_id", dataset.getDatasetId())
                    ).stream().map(DatasetTags::getTag).collect(Collectors.toList());;
                    response.setTags(tags);

                    return response;
                }).collect(Collectors.toList());

        // 返回分页结果
        Page<DatasetResponse> datasetResponsePage = new Page<>(page, size);
        datasetResponsePage.setRecords(datasetResponses);
        datasetResponsePage.setTotal(datasetPage.getTotal());
        datasetResponsePage.setCurrent(datasetPage.getCurrent());
        datasetResponsePage.setSize(datasetPage.getSize());

        return datasetResponsePage;
    }

    @PostMapping("/createDataset")
    public R createDataset(@AuthenticationPrincipal UserDetails userDetails,
                           @RequestParam("dataset") String datasetJson,
                           @RequestParam("files") List<MultipartFile> files) throws Exception{
        // 解析 JSON 数据
        ObjectMapper objectMapper = new ObjectMapper();
        DatasetRequest dataset = objectMapper.readValue(datasetJson, DatasetRequest.class);

        User user = (User) userDetails;
        if(datasetMetadataService.createDataset(user, dataset, files))
        {
            return R.ok("数据集创建成功");
        }
        return R.failure("数据集创建失败");
    }

    @PostMapping("/deleteDataset")
    public R deleteDataset(@RequestParam("id") Long id){
        if(datasetMetadataService.deleteDataset(id))
        {
            return R.ok("数据集删除成功");
        }
        return R.failure("数据集删除失败");
    }
}
